package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wrupple.muba.catalogs.client.module.services.logic.FieldConversionStrategyProvider;
import com.wrupple.muba.common.client.FieldConversionStrategy;
import com.wrupple.vegetate.domain.CatalogDescriptor;
import com.wrupple.vegetate.domain.FieldDescriptor;

public class FieldConversionStrategyProviderImpl implements
		FieldConversionStrategyProvider {
	private static FieldConversionStrategy textConversion;
	private static FieldConversionStrategy defaultConversion;

	@Inject
	public FieldConversionStrategyProviderImpl(
			Provider<FieldConversionStrategy> conversionProvider) {
		super();
		defaultConversion = conversionProvider.get();
		textConversion = conversionProvider.get();
		textConversion.setNullAsEmptyString(true);
		textConversion.setEmptyStringsAsNull(true);
		textConversion.setNumberAsString(true);
	}

	@Override
	public FieldConversionStrategy getFieldConversionStrategy(
			String fieldid,CatalogDescriptor catalog) {
		FieldConversionStrategy conversion = defaultConversion;
		FieldDescriptor field = catalog.getFieldDescriptor(fieldid);
		if (isImageField(fieldid)) {
			conversion = textConversion;
		}else
		if (isKeyField(field,catalog)) {
			conversion = textConversion;
			//TODO isManagedKeyField (containes foreign object metadata, such as name)
		}else
		if (isTextField(field)) {
			conversion = textConversion;
		}
		return conversion;
	}

	private boolean isImageField(String field) {
		return "image".equals(field);
	}

	private boolean isTextField(FieldDescriptor field) {
		return "text".equals(field.getWidget());
	}

	private boolean isKeyField(FieldDescriptor field, CatalogDescriptor catalog) {
		String keyField = catalog.getKeyField();
		if(keyField==null){
			keyField="id";

		}
		return field.getForeignCatalog() != null
				|| field.isKey()
				|| keyField.equals(field.getId());
	}

}
